/**
 * 数据处理工具函数
 */

/**
 * 格式化数值
 * @param {number} value - 数值
 * @param {string} type - 格式类型 (currency, percentage, number)
 * @returns {string} 格式化后的字符串
 */
export function formatNumber(value, type = 'number') {
  if (value == null || isNaN(value)) return '-'
  
  switch (type) {
    case 'currency':
      return `¥${Number(value).toLocaleString()}`
    case 'percentage':
      return `${(Number(value) * 100).toFixed(1)}%`
    case 'number':
    default:
      return Number(value).toLocaleString()
  }
}

/**
 * 格式化日期
 * @param {string|Date} date - 日期
 * @param {string} format - 格式类型 (date, datetime, time)
 * @returns {string} 格式化后的日期字符串
 */
export function formatDate(date, format = 'date') {
  if (!date) return '-'
  
  const d = new Date(date)
  if (isNaN(d.getTime())) return '-'
  
  switch (format) {
    case 'datetime':
      return d.toLocaleString('zh-CN')
    case 'time':
      return d.toLocaleTimeString('zh-CN')
    case 'date':
    default:
      return d.toLocaleDateString('zh-CN')
  }
}

/**
 * 获取字段的数据类型
 * @param {any} value - 字段值
 * @returns {string} 数据类型
 */
export function getDataType(value) {
  if (value == null) return 'unknown'
  
  if (typeof value === 'number') return 'number'
  if (typeof value === 'boolean') return 'boolean'
  
  // 检查是否为日期
  if (typeof value === 'string') {
    const dateRegex = /^\d{4}-\d{2}-\d{2}$/
    if (dateRegex.test(value) || !isNaN(Date.parse(value))) {
      return 'date'
    }
  }
  
  return 'string'
}

/**
 * 聚合数据
 * @param {Array} data - 原始数据
 * @param {Array} groupFields - 分组字段
 * @param {Array} measures - 度量值配置
 * @returns {Array} 聚合后的数据
 */
export function aggregateData(data, groupFields = [], measures = []) {
  if (!data || !data.length) return []
  
  if (!groupFields.length) {
    // 没有分组字段，计算总计
    const result = {}
    measures.forEach(measure => {
      const values = data.map(item => Number(item[measure.field]) || 0)
      result[measure.field] = calculateAggregation(values, measure.aggregation)
    })
    return [result]
  }
  
  // 按分组字段聚合
  const groups = {}
  data.forEach(item => {
    const key = groupFields.map(field => item[field]).join('|')
    if (!groups[key]) {
      groups[key] = {
        items: [],
        ...groupFields.reduce((obj, field) => {
          obj[field] = item[field]
          return obj
        }, {})
      }
    }
    groups[key].items.push(item)
  })
  
  return Object.values(groups).map(group => {
    const result = { ...group }
    delete result.items
    
    measures.forEach(measure => {
      const values = group.items.map(item => Number(item[measure.field]) || 0)
      result[measure.field] = calculateAggregation(values, measure.aggregation)
    })
    
    return result
  })
}

/**
 * 计算聚合值
 * @param {Array} values - 数值数组
 * @param {string} aggregation - 聚合类型
 * @returns {number} 聚合结果
 */
function calculateAggregation(values, aggregation) {
  if (!values.length) return 0
  
  switch (aggregation) {
    case 'sum':
      return values.reduce((sum, val) => sum + val, 0)
    case 'avg':
      return values.reduce((sum, val) => sum + val, 0) / values.length
    case 'count':
      return values.length
    case 'max':
      return Math.max(...values)
    case 'min':
      return Math.min(...values)
    default:
      return values.reduce((sum, val) => sum + val, 0)
  }
}

/**
 * 筛选数据
 * @param {Array} data - 原始数据
 * @param {Array} filters - 筛选器配置
 * @returns {Array} 筛选后的数据
 */
export function filterData(data, filters = []) {
  if (!data || !data.length || !filters.length) return data
  
  return data.filter(item => {
    return filters.every(filter => {
      const fieldValue = item[filter.field]
      
      // 多选筛选
      if (filter.selectedValues && filter.selectedValues.length > 0) {
        return filter.selectedValues.includes(fieldValue)
      }
      
      // 单值筛选
      if (filter.value != null && filter.value !== '') {
        return applyFilterOperator(fieldValue, filter.value, filter.operator)
      }
      
      return true
    })
  })
}

/**
 * 应用筛选操作符
 * @param {any} fieldValue - 字段值
 * @param {any} filterValue - 筛选值
 * @param {string} operator - 操作符
 * @returns {boolean} 是否匹配
 */
function applyFilterOperator(fieldValue, filterValue, operator) {
  switch (operator) {
    case 'equals':
      return fieldValue === filterValue
    case 'not_equals':
      return fieldValue !== filterValue
    case 'contains':
      return String(fieldValue).toLowerCase().includes(String(filterValue).toLowerCase())
    case 'greater':
      return Number(fieldValue) > Number(filterValue)
    case 'less':
      return Number(fieldValue) < Number(filterValue)
    case 'greater_equal':
      return Number(fieldValue) >= Number(filterValue)
    case 'less_equal':
      return Number(fieldValue) <= Number(filterValue)
    case 'after':
      return new Date(fieldValue) > new Date(filterValue)
    case 'before':
      return new Date(fieldValue) < new Date(filterValue)
    default:
      return true
  }
}

/**
 * 获取唯一值
 * @param {Array} data - 数据数组
 * @param {string} field - 字段名
 * @returns {Array} 唯一值数组
 */
export function getUniqueValues(data, field) {
  if (!data || !data.length) return []
  
  const values = data.map(item => item[field]).filter(val => val != null)
  return [...new Set(values)].sort()
}

/**
 * 生成颜色调色板
 * @param {number} count - 颜色数量
 * @returns {Array} 颜色数组
 */
export function generateColorPalette(count) {
  const baseColors = [
    '#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399',
    '#36CFC9', '#722ED1', '#13C2C2', '#52C41A', '#FA8C16',
    '#F759AB', '#40A9FF', '#73D13D', '#FFEC3D', '#FF7875'
  ]
  
  if (count <= baseColors.length) {
    return baseColors.slice(0, count)
  }
  
  // 如果需要更多颜色，生成渐变色
  const colors = [...baseColors]
  while (colors.length < count) {
    const baseColor = baseColors[colors.length % baseColors.length]
    const variation = generateColorVariation(baseColor)
    colors.push(variation)
  }
  
  return colors.slice(0, count)
}

/**
 * 生成颜色变体
 * @param {string} baseColor - 基础颜色
 * @returns {string} 变体颜色
 */
function generateColorVariation(baseColor) {
  // 简单的颜色变体生成逻辑
  const hex = baseColor.replace('#', '')
  const r = parseInt(hex.substr(0, 2), 16)
  const g = parseInt(hex.substr(2, 2), 16)
  const b = parseInt(hex.substr(4, 2), 16)
  
  // 调整亮度
  const factor = 0.8 + Math.random() * 0.4 // 0.8 - 1.2
  const newR = Math.min(255, Math.floor(r * factor))
  const newG = Math.min(255, Math.floor(g * factor))
  const newB = Math.min(255, Math.floor(b * factor))
  
  return `#${newR.toString(16).padStart(2, '0')}${newG.toString(16).padStart(2, '0')}${newB.toString(16).padStart(2, '0')}`
}

/**
 * 导出数据为CSV
 * @param {Array} data - 数据数组
 * @param {string} filename - 文件名
 */
export function exportToCSV(data, filename = 'data.csv') {
  if (!data || !data.length) return
  
  const headers = Object.keys(data[0])
  const csvContent = [
    headers.join(','),
    ...data.map(row => headers.map(header => `"${row[header] || ''}"`).join(','))
  ].join('\n')
  
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  
  if (link.download !== undefined) {
    const url = URL.createObjectURL(blob)
    link.setAttribute('href', url)
    link.setAttribute('download', filename)
    link.style.visibility = 'hidden'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
  }
}

